#!/usr/bin/perl

# 2017.07.09 modified by Guo Xiang Yong, for online display and with the answers.

use Data::Dumper;
use List::Util;
use POSIX qw(strftime);

$datestring = strftime "%Y-%m-%d_%H%M%S", localtime;
$debug=0;

@total=<>;  # 读取制定文件

$oneline=join(undef,@total);
@orderd=split(/\n\n/,$oneline);  # 空行分段
$tt=@orderd;

%ANSWER=(A,0,B,1,C,2,D,3,E,4,F,5,G,6);  # 答案和数组的对应
%ANSWER1=(0,A,1,B,2,C,3,D,4,E,5,F,6,G);  # 答案和数组的对应

# 使用shuffle 打乱数组的顺序，随机出现
@orderd=List::Util::shuffle @orderd;
if($debug==1){
	$QF=STDOUT;
	$AF=STDOUT;
}else{
	open($QF,">$datestring.questions");
	open($AF,">$datestring.answer");
}

$number=1;
foreach $question(@orderd){
	$answer=$1 if($question=~/Answer: (.*)/);  # 获得答案
	# 去掉答案部分
	$question=~s/Answer: .*//;
	
	# 替换新的题目顺序号
	$question=~s/\d{1,2}]\./$number\)\. /;
	
	# 获得ABCD的选项内容，如果是填空提，忽略该步骤
	if($question=~/(A\..*B\..*C\..*.)/){
		$option=$1;
		($answer,$newo)=newOptions($option,$answer);
		$question=~s/A\..*B\..*C\..*./$newo/;  # 替换新的答案顺序
	}

	
	print $QF "$question\n";
	print $AF "$number\). Answer: $answer \n";
	$number++;	
}
close($AF);
close($QF);
print "Create ...  $datestring\n";
# 新的Options的顺序输出
sub newOptions{
	my $option=shift;
	my $answer=shift;
	my @temp=split(/[A-E]\./,$option);  # 拆解选项，第0个数组为空，忽略，坐标以1开始计算
	shift @temp;  # 去除第一个空元素。

	my @options=map(&chmop1($_),@temp); # 将选项中的前后空格
	my $theanswer=$options[$ANSWER{$answer}];  # 获得答案的内容。
	my @options=List::Util::shuffle @options;  # 打乱顺序
	my $newresult="";  # 准备返回结果
	my $newanswer="";
	for(my $i=0;$i<scalar(@options);$i++){
		$newanswer=$ANSWER1{$i} if($options[$i] eq $theanswer);
		$newresult=$newresult.$ANSWER1{$i}.". ".$options[$i]." ";
	}
	return ($newanswer,$newresult);
}

# 删除字符串前和后的空格
sub chmop1{
	$inp=shift;
	$inp=~s/(^\s+|\s+$)//g;
	return $inp;
}
